package cn.easyar.samples.helloarqrcode.remote;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.internal.Utils;
import cn.easyar.samples.helloarqrcode.MyApplication;
import cn.easyar.samples.helloarqrcode.R;
import cn.easyar.samples.helloarqrcode.adpter.ImageAdapter;
import cn.easyar.samples.helloarqrcode.adpter.MessagesAdapter;
import cn.easyar.samples.helloarqrcode.bean.ImageBean;
import cn.easyar.samples.helloarqrcode.bean.MessageFileBean;
import cn.easyar.samples.helloarqrcode.util.BadgeHelper;
import cn.easyar.samples.helloarqrcode.util.GlobalParams;
import cn.easyar.samples.helloarqrcode.util.SpaceItemDecoration;
import cn.easyar.samples.helloarqrcode.xunfei.VoiceBean;
import cn.easyar.samples.helloarqrcode.xunfei.VoiceOrder;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.rtc.Constants;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.mediaio.IVideoFrameConsumer;
import io.agora.rtc.video.VideoCanvas;
import io.agora.rtc.video.VideoEncoderConfiguration;

public class VideoChatViewActivity extends AppCompatActivity implements IVideoFrameConsumer {



    private static final String LOG_TAG = VideoChatViewActivity.class.getSimpleName();

    private static final int PERMISSION_REQ_ID_RECORD_AUDIO = 22;
    private static final int PERMISSION_REQ_ID_CAMERA = PERMISSION_REQ_ID_RECORD_AUDIO + 1;

    private RtcEngine mRtcEngine;// Tutorial Step 1
    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() { // Tutorial Step 1
        @Override
        public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) { // Tutorial Step 5
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.i("=========", "run: 第一帧");
                    setupRemoteVideo(uid);
                }
            });
        }

        @Override
        public void onUserJoined(int uid, int elapsed) {
            super.onUserJoined(uid, elapsed);
            userNum++;
        }

        //用户退出时
        @Override
        public void onUserOffline(final int uid, int reason) { // Tutorial Step 7
            int a = uid;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                }
            });

            userNum--;
            if(userNum==0){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AlertDialog dialog = new AlertDialog.Builder(VideoChatViewActivity.this)
                                .setTitle("")   //R.string.vt_dialog_logout_title
                                .setMessage("所有人已离开!")
                                .setPositiveButton(R.string.vt_dialog_btn_positive, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        onRemoteUserLeft();
                                    }
                                })
                                .setNegativeButton(R.string.vt_dialog_btn_cancel, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        // Nothing to do
                                    }
                                })
                                .create();
                        dialog.show();

                    }
                });
            }

        }

        @Override
        public void onUserMuteVideo(final int uid, final boolean muted) { // Tutorial Step 10
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    onRemoteUserVideoMuted(uid, muted);
                }
            });
        }


        //检测网络

        /**
         * QUALITY_UNKNOWN(0)：质量未知
         QUALITY_EXCELLENT(1)：质量极好
         QUALITY_GOOD(2)：用户主观感觉和极好差不多，但码率可能略低于极好
         QUALITY_POOR(3)：用户主观感受有瑕疵但不影响沟通
         QUALITY_BAD(4)：勉强能沟通但不顺畅
         QUALITY_VBAD(5)：网络质量非常差，基本不能沟通
         QUALITY_DOWN(6)：完全无法沟通
         * @param uid
         * @param txQuality
         * @param rxQuality
         */
        @Override
        public void onNetworkQuality(int uid, int txQuality, int rxQuality) {
            super.onNetworkQuality(uid, txQuality, rxQuality);
            Logger.i("网络检测" + uid + "  " + txQuality + "  " + rxQuality);
            //0为本地用户
            if (uid == 0) {
                if (txQuality >= 3 || rxQuality >= 3) {
//                    Toasty.info(VideoChatViewActivity.this,"当前网络似乎不太好").show();
                    iv_network.setBackground(getResources().getDrawable(R.drawable.shape_color_btn_red));
                } else {
                    iv_network.setBackground(getResources().getDrawable(R.drawable.shape_color_btn_green));
                }
            }
        }
    };
    private String channelName;
    private String account;
    private AgoraAPIOnlySignal mAgoraAPI;
    private RecyclerView rv_screenshot_list, rv_messages_list;
    private TextView tv_name;
    private String guidName;
    private ImageAdapter imageAdapter;
    private List<ImageBean> imageList = new ArrayList<>();
    private ImageView iv_big_img;
    private ImageView iv_network;
    private int userNum = 0;//当前频道总人数
    private ImageButton ib_back, ib_messages;
    private TextView tv_invitation_tips;
    private AlphaAnimation alphaAnimation;
    private MessagesAdapter messagesAdapter;
    private LinearLayout ll_messages_content;
    private boolean isMessageListShow = false;
    private ImageButton btn_messages_close;
    private ImageView img_messages_tips;
    private ArrayList<MessageFileBean> messageList = new ArrayList<>();
    private int unReadMessageNum = 0;
    private BadgeHelper badgeHelperE;
    private NumberProgressBar number_progress_bar;
    private RelativeLayout rl_message;

    public int lastIndex = -1;
    private FrameLayout fl_remote_video;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //去掉Activity上面的状态栏
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN);
        setContentView(R.layout.activity_video_chat_view);
        EventBus.getDefault().register(this);
        VoiceOrder.activityList.add("VideoChatViewActivity");
        initView();
        initData();
        if (checkSelfPermission(Manifest.permission.RECORD_AUDIO, PERMISSION_REQ_ID_RECORD_AUDIO) && checkSelfPermission(Manifest.permission.CAMERA, PERMISSION_REQ_ID_CAMERA)) {
            initAgoraEngineAndJoinChannel();
        }
//        messageHandler.postDelayed(messageRunnable, 3000);
    }
    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }



    public void startAlphaAnimation(){
        if(alphaAnimation==null){
            alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
            alphaAnimation.setDuration(2500);
            alphaAnimation.setRepeatMode(AlphaAnimation.INFINITE);
        }
        tv_invitation_tips.startAnimation(alphaAnimation);
        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                tv_invitation_tips.clearAnimation();
                tv_invitation_tips.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void initView() {
        iv_network = findViewById(R.id.iv_network);
        iv_big_img = findViewById(R.id.iv_big_img);
        rv_screenshot_list = findViewById(R.id.rv_screenshot_list);
        tv_name = findViewById(R.id.tv_name);
        ib_back = findViewById(R.id.ib_back);
        tv_invitation_tips = findViewById(R.id.tv_invitation_tips);
        ib_messages = findViewById(R.id.ib_messages);
        rv_messages_list = findViewById(R.id.rv_messages_list);
        ll_messages_content = findViewById(R.id.ll_messages_content);
        btn_messages_close = findViewById(R.id.btn_messages_close);
        img_messages_tips = findViewById(R.id.img_messages_tips);
        number_progress_bar = findViewById(R.id.number_progress_bar);
        rl_message = findViewById(R.id.rl_message);
        fl_remote_video = findViewById(R.id.fl_remote_video);



        imageAdapter = new ImageAdapter(imageList, this);
        rv_screenshot_list.setLayoutManager(new LinearLayoutManager(this));
        rv_screenshot_list.addItemDecoration(new SpaceItemDecoration(0,10));
        rv_screenshot_list.setAdapter(imageAdapter);
        imageAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        rv_screenshot_list.requestFocus();

        messagesAdapter = new MessagesAdapter(messageList,this);
        messagesAdapter.setHasStableIds(true);
        rv_messages_list.setItemAnimator(null);
        rv_messages_list.setLayoutManager(new LinearLayoutManager(this));
        rv_messages_list.setAdapter(messagesAdapter);
        rv_messages_list.scrollToPosition(messagesAdapter.getItemCount()-1);
        rv_messages_list.setFocusable(false);
        rv_messages_list.setFocusableInTouchMode(false);

        btn_messages_close.setNextFocusDownId(R.id.btn_messages_close);
        btn_messages_close.setNextFocusUpId(R.id.btn_messages_close);
        btn_messages_close.setNextFocusLeftId(R.id.btn_messages_close);
        badgeHelperE = new BadgeHelper(this)
                .setBadgeType(BadgeHelper.Type.TYPE_TEXT);//注意 isIgnoreTargetPadding=true时 和 setBadgeMargins 不能同时使用
        badgeHelperE.bindToTargetView(img_messages_tips);
        badgeHelperE.setBadgeMargins(0,-5,-5,0);
        badgeHelperE.setVisibility(View.GONE);

        imageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //更新item状态
                ImageBean item = (ImageBean) adapter.getItem(position);
                item.isShow = true;
                adapter.notifyItemChanged(position);

                RequestOptions options = new RequestOptions();
                options.placeholder(R.mipmap.ic_loading);//图片加载出来前，显示的图片
                /*显示大图*/
                if (iv_big_img.getVisibility() != View.VISIBLE) {
                    Glide.with(VideoChatViewActivity.this).load(item.url).apply(options).into(iv_big_img);
                    iv_big_img.setVisibility(View.VISIBLE);
                } else {
                    iv_big_img.setVisibility(View.GONE);
                }

//                Intent intent = new Intent(VideoChatViewActivity.this,BigImageActivity.class);
//                intent.putExtra("ImageUrl", item.url);
//                startActivity(intent);
            }
        });


        //消息列表显示或者隐藏
        ib_messages.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isMessageListShow){
                    rl_message.setVisibility(View.GONE);
                    rv_screenshot_list.setVisibility(View.GONE);
                    btn_messages_close.requestFocus();
                    ib_messages.setFocusable(false);
                    ib_messages.setFocusable(false);
                    ib_back.setFocusableInTouchMode(false);
                    ib_back.setFocusable(false);
                    rv_screenshot_list.setFocusableInTouchMode(false);
                    rv_screenshot_list.setFocusable(false);
                    ll_messages_content.setVisibility(View.VISIBLE);
                    rv_messages_list.scrollToPosition(messagesAdapter.getItemCount()-1);
                    lastIndex = messagesAdapter.getItemCount()-1;
                    messagesAdapter.notifyItemChanged(lastIndex);
                    isMessageListShow = !isMessageListShow;
                }
            }
        });

        btn_messages_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isMessageListShow){

                    closeMessagesList();
                }
            }
        });

    }


    private void initData() {
        channelName = getIntent().getStringExtra("channelName");
        account = getIntent().getStringExtra("account");
        guidName = getIntent().getStringExtra("guidName");
        tv_name.setText("当前指导者:"+guidName);
    }

    /**
     * 隐藏消息列表
     */
    private void closeMessagesList(){
        ib_back.setFocusableInTouchMode(true);
        ib_back.setFocusable(true);
        rl_message.setVisibility(View.VISIBLE);
        rv_screenshot_list.setVisibility(View.VISIBLE);
        ib_messages.setFocusable(true);
        rv_screenshot_list.setFocusableInTouchMode(true);
        rv_screenshot_list.setFocusable(true);
        isMessageListShow = !isMessageListShow;
        unReadMessageNum = 0;
        badgeHelperE.setVisibility(View.GONE);
        ib_messages.requestFocus();
        ll_messages_content.setVisibility(View.GONE);
    }

    /**
     * 刷新消息列表
     */
    private void updateMessagesList(){
        messagesAdapter.notifyDataSetChanged();
    }

    /**
     * 下载文件
     */
    BaseDownloadTask singleTask;
    String mFilePath;
    public int singleTaskId = 0;
    private boolean isDownload = false;
    public void startDown(String fileUrl, String fileType, String fileName) {
        if(isDownload)
            return;
        File file = null;
        try {
            file = new File(FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "shangu_save");
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e+"");
        }
        isDownload = true;

        mFilePath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "shangu_save" + File.separator + fileName;
        singleTask = FileDownloader.getImpl().create(fileUrl)
//                .setPath(mSinglePath,false)
                .setPath(mFilePath)
                .setCallbackProgressTimes(300)
                .setMinIntervalUpdateSpeed(400)
                //.setWifiRequired(isWifiRequired:boolean)//设置任务是否只允许在Wifi网络环境下进行下载。 默认值 false
                //.pause(void)//暂停下载任务(也可以理解为停止下载，但是在start的时候默认会断点续传)
                //.setAutoRetryTimes(autoRetryTimes:int)//当请求或下载或写文件过程中存在错误时，自动重试次数，默认为0次
                //.setSyncCallback(syncCallback:boolean)//如果设为true, 所有FileDownloadListener中的回调都会直接在下载线程中回调而不抛到ui线程, 默认为false
//                .setForceReDownload(true)//是否强制重新下载
                //.isReusedOldFile(void):boolean//判断是否是直接使用了旧文件(检测是有效文件)，没有启动下载
                //.setTag()
                .setForceReDownload(false)
                .setListener(new FileDownloadSampleListener() {
                    //等待，已经进入下载队列
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei", "pending taskId:" + task.getId() + ",soFarBytes:" + soFarBytes + ",totalBytes:" + totalBytes + ",percent:" + soFarBytes * 1.0 / totalBytes);

                    }

                    //下载进度回调
                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei", "progress taskId:" + task.getId() + ",soFarBytes:" + soFarBytes + ",totalBytes:" + totalBytes + ",percent:" + soFarBytes * 1.0 / totalBytes + ",speed:" + task.getSpeed());
                        number_progress_bar.setProgress(1);
                        if(number_progress_bar.getVisibility() == View.GONE){
                            number_progress_bar.setVisibility(View.VISIBLE);
                        }
                        int number = soFarBytes * 100 / totalBytes;
                        number_progress_bar.setProgress(number);
                    }

                    //在完成前同步调用该方法，此时已经下载完成
                    @Override
                    protected void blockComplete(final BaseDownloadTask task) {
                        Log.d("feifei", "blockComplete taskId:" + task.getId() + ",filePath:" + task.getPath() + ",fileName:" + task.getFilename() + ",speed:" + task.getSpeed() + ",isReuse:" + task.reuse());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                number_progress_bar.setVisibility(View.GONE);
                                isDownload = false;
                                openFile(VideoChatViewActivity.this, task.getPath());
                            }
                        });

                        Logger.e("线程Thread.currentThread().getName() :" + Thread.currentThread().getName());
                    }

                    //完成整个下载过程
                    @Override
                    protected void completed(BaseDownloadTask task) {
                        Log.d("feifei", "completed taskId:" + task.getId() + ",isReuse:" + task.reuse());
                        isDownload = false;
                    }

                    //暂停下载
                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei", "paused taskId:" + task.getId() + ",soFarBytes:" + soFarBytes + ",totalBytes:" + totalBytes + ",percent:" + soFarBytes * 1.0 / totalBytes);
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Log.d("feifei", "error taskId:" + task.getId() + ",e:" + e.getLocalizedMessage());
//                        loadingError();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                number_progress_bar.setVisibility(View.GONE);
                                isDownload = false;
                                Toast.makeText(VideoChatViewActivity.this, "该文件不支持打开", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    //在下载队列中(正在等待/正在下载)已经存在相同下载连接与相同存储路径的任务
                    @Override
                    protected void warn(BaseDownloadTask task) {
                        Log.d("feifei", "warn taskId:" + task.getId());
                    }
                });
        singleTaskId = singleTask.start();

    }

    /**
     * 通过相应的app打开文件
     * @param context
     */
    public void openFile(Context context, String filePath) {
        try {
            File file = new File(filePath);
            Intent openintent = new Intent();
            openintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            String type = getMIMEType(file);
            openintent.setDataAndType(/* uri */Uri.fromFile(file), type);
            context.startActivity(openintent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context, "sorry附件不能打开，请下载相关软件！", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 点击大图关闭
     * @param view
     */
    public void onClickBigImg(View view) {
        if (view.getVisibility() == View.VISIBLE) {
            view.setVisibility(View.GONE);
        }
    }


    private void initAgoraEngineAndJoinChannel() {
        //初始化信令
        mAgoraAPI = MyApplication.the().getmAgoraAPI();
        //初始化视频
        initializeAgoraEngine();     // Tutorial Step 1
        setupVideoProfile();         // Tutorial Step 2
        setupLocalVideo();           // Tutorial Step 3
        joinChannel();               // Tutorial Step 4
    }
    StringBuilder stringBuilder = new StringBuilder("");


    /**
     * 当用户离开
     */
    // Tutorial Step 7
    private void onRemoteUserLeft() {

        finish();

    }


    public boolean checkSelfPermission(String permission, int requestCode) {
        Log.i(LOG_TAG, "checkSelfPermission " + permission + " " + requestCode);
        if (ContextCompat.checkSelfPermission(this,
                permission)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{permission},
                    requestCode);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults) {
        Log.i(LOG_TAG, "onRequestPermissionsResult " + grantResults[0] + " " + requestCode);

        switch (requestCode) {
            case PERMISSION_REQ_ID_RECORD_AUDIO: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkSelfPermission(Manifest.permission.CAMERA, PERMISSION_REQ_ID_CAMERA);
                } else {
                    showLongToast("No permission for " + Manifest.permission.RECORD_AUDIO);
                    finish();
                }
                break;
            }
            case PERMISSION_REQ_ID_CAMERA: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initAgoraEngineAndJoinChannel();
                } else {
                    showLongToast("No permission for " + Manifest.permission.CAMERA);
                    finish();
                }
                break;
            }
        }
    }

    public final void showLongToast(final String msg) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        });
    }



    // Tutorial Step 10
    public void onLocalVideoMuteClicked(View view) {
        ImageView iv = (ImageView) view;
        if (iv.isSelected()) {
            iv.setSelected(false);
            iv.clearColorFilter();
        } else {
            iv.setSelected(true);
            iv.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
        }
        //暂停本地视频流 true: 不发送本地视频流 false: 发送本地视频流
        mRtcEngine.muteLocalVideoStream(iv.isSelected());

        FrameLayout container = (FrameLayout) findViewById(R.id.local_video_view_container);
        SurfaceView surfaceView = (SurfaceView) container.getChildAt(0);
        surfaceView.setZOrderMediaOverlay(!iv.isSelected());
        surfaceView.setVisibility(iv.isSelected() ? View.GONE : View.VISIBLE);
    }

    // Tutorial Step 9
    public void onLocalAudioMuteClicked(View view) {
        ImageView iv = (ImageView) view;
        if (iv.isSelected()) {
            iv.setSelected(false);
            iv.clearColorFilter();
        } else {
            iv.setSelected(true);
            iv.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
        }

        mRtcEngine.muteLocalAudioStream(iv.isSelected());
    }

    /**
     * 设置远程视频
     *
     * @param uid
     */
    // Tutorial Step 5
    private void setupRemoteVideo(int uid) {
        FrameLayout container = (FrameLayout) findViewById(R.id.local_video_view_container);
        if (fl_remote_video.getChildCount() >= 1) {
            return;
        }
        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
        fl_remote_video.addView(surfaceView);
        //调用 setupRemoteVideo() 方法设置本地看到的远端用户的视频视图
        mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
        surfaceView.setTag(uid); // 为了标记目标
    }

    // Tutorial Step 8
    public void onSwitchCameraClicked(View view) {
        mRtcEngine.switchCamera();
    }

    // Tutorial Step 6
    public void onEncCallClicked(View view) {
        finish();
    }

    // Tutorial Step 1
    private void initializeAgoraEngine() {
        try {
            mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
        } catch (Exception e) {
            Log.e(LOG_TAG, Log.getStackTraceString(e));

            throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
        }
    }

    // Tutorial Step 2
    private void setupVideoProfile() {
        mRtcEngine.enableVideo();
//        mRtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_360P, false);//视频分辨率


        VideoEncoderConfiguration.VideoDimensions vd_1280x720 = VideoEncoderConfiguration.VD_1280x720;
        VideoEncoderConfiguration.FRAME_RATE frameRateFps15 = VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15;
        int standardBitrate = VideoEncoderConfiguration.STANDARD_BITRATE;
        VideoEncoderConfiguration.ORIENTATION_MODE orientationModeAdaptive = VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_LANDSCAPE;
        VideoEncoderConfiguration videoEncoderConfiguration = new VideoEncoderConfiguration(vd_1280x720, frameRateFps15, standardBitrate, orientationModeAdaptive);
        mRtcEngine.setVideoEncoderConfiguration(videoEncoderConfiguration);
    }

    // Tutorial Step 3
    private void setupLocalVideo() {
        FrameLayout container = (FrameLayout) findViewById(R.id.local_video_view_container);
        //todo
        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
//        surfaceView.setZOrderMediaOverlay(true);
        container.addView(surfaceView);
        //设置本地视频视频
        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, 0));
        //镜像问题调用
        mRtcEngine.setParameters("{\"che.video.localViewMirrorSetting\":\"disableMirror\"}");
        //转换摄像头
        mRtcEngine.switchCamera();

    }

    // Tutorial Step 4

    /**
     * joinChannel(String token,String channelName,String optionalInfo,int optionalUid);
     * channelName 房间名 同一房间代表同一通话
     * optionalInfo 房间信息
     * optionalUid 用户id
     */
    private void joinChannel() {
        int userId = GlobalParams.getUserId();
        Logger.i("channelName："+channelName+" userId:"+userId);
        //与web互通时加入以下代码
        mRtcEngine.setChannelProfile(1);
        mRtcEngine.setClientRole(Constants.CLIENT_ROLE_BROADCASTER);
        mRtcEngine.enableWebSdkInteroperability(true);

        mRtcEngine.joinChannel(null, channelName, "Extra Optional Data", 111111); // if you do not specify the uid, we will generate the uid for you
    }


    //退出
    // Tutorial Step 6
    private void leaveChannel() {
        //用户必须调用 leaveChannel() 方法退出当前通话，才能进入下一个频道。
        mRtcEngine.leaveChannel();
        MyApplication.the().getmAgoraAPI().channelLeave(channelName);//离开
    }


    //结束呼叫
    private void callOutHangup() {
        if (mAgoraAPI != null)
            mAgoraAPI.channelInviteEnd(channelName, account, 0);
    }

    @Override
    public void onBackPressed() {
        if(isMessageListShow){
            closeMessagesList();
        }else{
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setTitle("")   //R.string.vt_dialog_logout_title
                    .setMessage(R.string.vt_dialog_logout_message)
                    .setPositiveButton(R.string.vt_dialog_btn_positive, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            VideoChatViewActivity.super.onBackPressed();

                        }
                    })
                    .setNegativeButton(R.string.vt_dialog_btn_cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Nothing to do
                        }
                    })
                    .create();
            dialog.show();
        }
    }

    private MessageFileBean getMessageJson(String json){
        MessageFileBean messageFileBean = new MessageFileBean();
        try {
            JSONObject jsonObject = new JSONObject(json);
            messageFileBean.setFileType(jsonObject.getString("fileType"));
            messageFileBean.setSendType(jsonObject.getString("sendType"));
            messageFileBean.setUrl(jsonObject.getString("url"));
            messageFileBean.setFileName(jsonObject.getString("fileName"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return messageFileBean;
    }



    /**
     * 设置声网信令监听
     */
    private void addSignalingCallback() {
        if (mAgoraAPI == null) {
            return;
        }

        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {


            @Override
            public void onInviteEndByMyself(String channelID, String account, int uid) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        onEndCall();
                    }
                });
            }

            @Override
            public void onChannelUserJoined(String account, int uid) {
                super.onChannelUserJoined(account, uid);
            }

            /**
             * 收到频道消息回调
             * @param channelID 频道名
             * @param account 客户端定义的用户账号
             * @param uid 固定填 0
             * @param msg 消息正文
             */
            @Override
            public void onMessageChannelReceive(String channelID, final String account, final int uid, final String msg) {
                super.onMessageChannelReceive(channelID, account, uid, msg);
                Logger.i("接收到频道图片: account:"+account+" uid:"+uid+" msg:"+msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //---~~~~
                        MessageFileBean messageFileBean = getMessageJson(msg);
                        if(messageFileBean.getFileType()!=null) {
                            if (messageFileBean.getSendType().equals("file")) {
                                unReadMessageNum++;
                                if (badgeHelperE.getVisibility() == View.GONE) {
                                    badgeHelperE.setVisibility(View.VISIBLE);
                                }
                                badgeHelperE.setBadgeNumber(unReadMessageNum);//数字
                                messageList.add(messageFileBean);
                                updateMessagesList();
                            } else {
                                //判断集合中图片数量是否>=3
                                if (imageList.size() >= 3) {
                                    //数量大于3删除第一个
                                    imageAdapter.remove(0);
                                    imageAdapter.addData(imageAdapter.getData().size(), new ImageBean(messageFileBean.getUrl()));
                                    //添加最后一个
                                } else {
                                    imageAdapter.addData(imageAdapter.getData().size(), new ImageBean(messageFileBean.getUrl()));
                                }
                            }
                        }
                    }
                });
            }

            //接收到发送过来的信息
            @Override
            public void onMessageInstantReceive(String account, int uid, final String msg) {
                super.onMessageInstantReceive(account, uid, msg);
                Logger.i("接收到图片: account:"+account+" uid:"+uid+" msg:"+msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //判断集合中图片数量是否>=3
                        if (imageList.size() >= 3) {
                            //数量大于3删除第一个
                            imageAdapter.remove(0);
                            imageAdapter.addData(imageAdapter.getData().size(),new ImageBean(msg));
                            //添加最后一个
                        } else {
                            imageAdapter.addData(imageAdapter.getData().size(),new ImageBean(msg));
                        }
                    }
                });
            }



        });


    }

    private void onEndCall() {
        finish();
    }


    @Override
    protected void onResume() {
        super.onResume();
        addSignalingCallback();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void voiceEvent(VoiceBean voiceBean) {
        if(voiceBean.str.contains(VoiceOrder.VOICE_QUIT)&&VoiceOrder.activityList.get(VoiceOrder.activityList.size()-1).equals("VideoChatViewActivity")){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        leaveChannel();
        RtcEngine.destroy();
        VoiceOrder.activityList.remove(VoiceOrder.activityList.size()-1);
        EventBus.getDefault().unregister(this);
        mRtcEngine = null;

//        EventBus.getDefault().post(new StartRecordBean());
    }

    @Override
    public void consumeByteBufferFrame(ByteBuffer byteBuffer, int i, int i1, int i2, int i3, long l) {

    }

    @Override
    public void consumeByteArrayFrame(byte[] bytes, int i, int i1, int i2, int i3, long l) {

    }

    @Override
    public void consumeTextureFrame(int i, int i1, int i2, int i3, int i4, long l, float[] floats) {

    }


    private String getMIMEType(File file) {

        String type = "*/*";
        String fName = file.getName();
        // 获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        /* 获取文件的后缀名 */
        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "")
            return type;
        // 在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MIME_MapTable.length; i++) {
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

    private final String[][] MIME_MapTable = {
            // {后缀名，MIME类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".docx",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-javascript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".pptx",
                    "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".prop", "text/plain"}, {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"}, {".rtf", "application/rtf"},
            {".sh", "text/plain"}, {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"}, {".txt", "text/plain"},
            {".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"}, {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/x-zip-compressed"}, {"", "*/*"}};
}
